<template>
    <div>
        <el-upload class="inline-block" :accept="accept" :action="uploadUrl"
            :data="uploadBody" :on-remove="handleRemove" :before-remove="beforeRemove" :on-exceed="handleExceed"
            :on-success="handleSuccess" :before-upload="beforeAvatarUpload" :file-list="fileList" :on-preview="handlePreview"
            :limit="limitNum">
            <el-button style="color:#fff" class="mgt-15" size="small" type="primary">上传<i
                    class="el-icon-upload el-icon--right"></i></el-button>
        </el-upload>
        <p class="color-grey fs-14 mgt-10">支持扩展名:{{ accept }}</p>
        <el-image-viewer v-if="showViewer" :on-close="() => {showViewer = false;}" :url-list="srcList" z-index="9999" />
    </div>
</template>

<script>
import { getBusiId, deleteFile } from "@/api/fileMng.js";
import commonUtil from "@/utils/common.js";
export default {
    props: {
        accept: {
            type: String,
            default: '.zip,.doc,.rar,.docx,.pdf,.jpg,.jpeg,.xls,.xlsx,.png'
        },
        busineesType: {
            type: String,
            default: ''
        },
        folder: {
            type: String,
            default: ''
        },
        busineesId: {
            type: String,
            default: ''
        },
        // fileUploadList: {
        //     type: Array,
        //     default: function () {
        //         return [];
        //     }
        // },
        limitNum:{
            type: Number,
            default: 5
        }
    },
    components: {
        "el-image-viewer": () => import("element-ui/packages/image/src/image-viewer"),
    },
    data() {
        return {
            uploadUrl: '',
            showViewer: false,
            uploadBody: {
                folder: '',
                busineesType: '',
                busineesId: ''
            },
            fileList: [],
            srcList: [],
            fileNameList:[],
            fileResponse:[],
            fileUploadList:[]
        }
    },
    watch: {
        fileUploadList() {
            console.log(this.fileUploadList,'子组件');
            if (this.fileUploadList.length != 0) {
                let fileList = [];
                this.fileUploadList.forEach(item => {
                    let obj = {
                        name: item.fileName
                    }
                    fileList.push(obj)
                })
                this.fileList = fileList
            } else {
                this.fileList = [];
            }
            console.log(this.fileList);
        },
        busineesId() {
            console.log(this.busineesId,'busineesId');
            if (this.busineesId && this.busineesId != '') {
                this.uploadBody.busineesId = this.busineesId
            } else {
                this.getBusinessId();
            }
        }
    },
    created() {
        this.getBusinessId();
    },
    mounted() {
        this.uploadUrl = commonUtil.getUploadFileUrl();
        this.uploadBody.folder = this.folder;
        this.uploadBody.busineesType = this.busineesType;
    },
    methods: {
        initUploadData(data){
            // 初始化businessId
            let { busineesId, fileUploadList } = data;
            this.fileUploadList = fileUploadList
            console.log(busineesId);
            if (busineesId && busineesId != '') {
                this.uploadBody.busineesId = busineesId
            } else {
                this.getBusinessId();
            }
            // 初始化fileUploadList
            if (fileUploadList.length != 0) {
                let fileList = [];
                fileUploadList.forEach(item => {
                    let obj = {
                        name: item.fileName
                    }
                    fileList.push(obj)
                })
                this.fileList = fileList
            } else {
                this.fileList = [];
            }
            // console.log(this.fileList);
        },
        beforeRemove(file, fileList) {
            if (file && file.status === "success") {
                this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    //执行删除操作
                    this.doDelete(file);
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            }
            return false;
        },
        handleRemove(file,fileList){
            this.doDelete(file);
        },
        doDelete(file){
            this.fileUploadList.forEach((item,index)=>{
                if (item.fileName === file.name){
                    var params = new FormData();
                    params.append('fileId', item.fileId);
                    deleteFile(params).then((res) => {
                        if (res.data.code !== '000000') {
                            return this.$message.error('删除失败，请稍后尝试!');
                        }
                        this.$message.success('删除成功!');
                        this.fileList.splice(index,1)
                    });
                }
            });
        },
        // 获取businessId
        getBusinessId() {
            getBusiId().then(({ data }) => {
                const { resultBody } = data;
                this.uploadBody.busineesId = resultBody.id;
            });
        },
        // 上传前校验
        beforeAvatarUpload(file){
            let is20M = file.size / 1024 / 1024 < 20;
            if (!is20M) {
                this.$message.error("上传单个文件大小不能超过20MB,请核查!");
                return false
            }
            console.log(this.fileNameList);
            console.log(typeof this.fileNameList);
            if (this.fileNameList.length!=0 && this.fileNameList.findIndex(v => v == file.name) != -1) {
                this.$message.error('请勿上传重复文件');
                return false;
            }
            this.fileNameList.push(file.name);
            // console.log(file.name);
            return true
        },
        // 上传文件下载及预览
        handlePreview(file) {
            let fileId = '';
            if (file.response && file.response.code == '000000') {
                fileId = file.response.resultBody.fileId;
            }
            if (fileId === '') {
                this.$message.error('暂未上传，不可下载');
                return;
            }
            const type = file.name.substring(file.name.lastIndexOf('.') + 1);
            // 判断文件类型
            if (type === 'jpg' || type === 'png' || type === 'jpeg') {
                let fd = new FormData();
                fd.append('file', file.raw);
                // 存储图片，点击确认按钮时统一上传
                this.showViewer = true;
                this.srcList = [];
                this.srcList.push(URL.createObjectURL(file.raw));
            } else {
                // 在当前浏览器直接下载
                commonUtil.downloadFileCommonTwo(fileId);
            }
        },
        // 图片上传
        handleSuccess(response, file, fileList) {
            if (response.code === '000000') {
                this.$message.success('文件上传成功')
                this.fileList = fileList;
                this.fileResponse.push(response.resultBody)
                let params = {
                    fileList: this.fileList,
                    busineesId: this.uploadBody.busineesId,
                    fileResponse: this.fileResponse
                }
                this.$emit('transferData', params);
            } else {
                this.$message.error('上传失败，请稍后重试');
            }
        },
        // 图片
        handleExceed(files, fileList) {
            if (fileList.length > this.limitNum || fileList.length == this.limitNum) {
                return this.$message.error(`限制选择${this.limitNum}个文件，本次选择了 ${fileList.length} 个文件`);
            }
        },
    },
}
</script>

<style lang="scss" scoped>

</style>